//
//  COHeViewController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/30.
//

import UIKit
import JXSegmentedView

class COHeViewController: COBaseViewController {
    private let id: Int
    private let sqVc: COHomeListViewController
    private let qaVc: COQAListViewController
    
    override var navShow: Bool {
        false
    }
    private var userInfo: COHomeListModel? {
        didSet {
            guard let userInfo = userInfo else {
                return
            }
            
            avatar.kf.setImage(with: URL(string: userInfo.sculpture))
            nameLabel.text = userInfo.nickName
            idLabel.text = "(ID:\(userInfo.userId))"
            followButton.isSelected = userInfo.follow
            if let id = COUserManager.userInfo?.id {
                followButton.isHidden = id == userInfo.id
            }
            if userInfo.level == "Advanced" {
                statusImageView.image = UIImage(named: "编组 16")
            } else if userInfo.level == "Beginner" {
                statusImageView.image = UIImage(named: "编组 2备份 5")
            } else if userInfo.level == "Intermediate" {
                statusImageView.image = UIImage(named: "编组 2备份 3")
            } else {
                statusImageView.image = UIImage(named: "")
            }
            
        }
    }
    init(id: Int) {
        self.id = id
        sqVc = COHomeListViewController(heId: id)
        qaVc = COQAListViewController(heId: id)
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        NotificationCenter.default.addObserver(self, selector: #selector(folloChange), name: .init("FolloSuccess"), object: nil)
        getMessage()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc
    private func folloChange() {
        getMessage()
    }
    
    override func configUI() {
        view.addSubview(backBtn)
        view.addSubview(tipButton)
        view.addSubview(avatar)
        view.addSubview(statusImageView)
        view.addSubview(stackView)
        view.addSubview(followButton)
        stackView.addArrangedSubviews([nameLabel, idLabel])
        view.addSubview(lineView)
        view.addSubview(segementView)
        view.addSubview(contentView)
        view.addSubview(chatButton)
        
        backBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(statusBarHeight + 5)
        }
        
        tipButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(statusBarHeight + 5)
        }
        
        avatar.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(71 + statusBarHeight)
            make.width.height.equalTo(80)
        }
        
        stackView.snp.makeConstraints { make in
            make.centerY.equalTo(avatar)
            make.left.equalTo(avatar.snp.right).offset(10)
            make.right.equalTo(followButton.snp.left).offset(-10)
        }
        
        followButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalTo(avatar)
        }
        
        statusImageView.snp.makeConstraints { make in
            make.bottom.equalTo(avatar.snp.bottom).offset(7)
            make.centerX.equalTo(avatar)
        }
        
        lineView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(avatar.snp.bottom).offset(31)
            make.height.equalTo(1)
        }
        
        segementView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().offset(0)
            make.top.equalTo(lineView.snp.bottom).offset(28)
            make.height.equalTo(25)
        }
        
        contentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(segementView.snp.bottom).offset(0)
        }
        
        chatButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-bottomSafeHeight-10)
        }
        followButton.setContentHuggingPriority(.required, for: .horizontal)
        followButton.setContentCompressionResistancePriority(.required, for: .horizontal)
    }
    
    
    private lazy var avatar: UIImageView = {
        let imgV = UIImageView()
        imgV.layer.masksToBounds = true
        imgV.layer.cornerRadius = 40
        return imgV
    }()
    
    private lazy var backBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 6"), for: .normal)
        btn.addTarget(self, action: #selector(backVC), for: .touchUpInside)
        return btn
    }()

    private lazy var statusImageView: UIImageView = {
        let imgV = UIImageView()
        return imgV
    }()
    
    private lazy var stackView: UIStackView = {
        let stackV = UIStackView()
        stackV.axis = .vertical
        stackV.spacing = 2
        return stackV
    }()
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .bold(22)
        label.textColor = .white
        return label
    }()
    
    private lazy var idLabel: UILabel = {
        let label = UILabel()
        label.font = .medium(12)
        label.textColor = .white.withAlphaComponent(0.5)
        return label
    }()
    
    private lazy var followButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 12"), for: .selected)
        btn.setImage(UIImage(named: "编组 22"), for: .normal)
        btn.addTarget(self, action: #selector(folloUser), for: .touchUpInside)
        return btn
    }()
    
    private lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .white.withAlphaComponent(0.15)
        return view
    }()
    
    private lazy var segementView: JXSegmentedView = {
        let view = JXSegmentedView()
        view.dataSource = dataSource
        view.listContainer = contentView
        return view
    }()
    
    private lazy var dataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = ["Square", "Q&A area"]
        dataSource.titleNormalFont = .bold(18)
        dataSource.titleNormalColor = .rgba(61, 51, 94)
        dataSource.titleSelectedFont = .bold(22)
        dataSource.titleSelectedColor = .white
        dataSource.itemSpacing = 35
        return dataSource
    }()
    
    private lazy var contentView: JXSegmentedListContainerView = {
        let view = JXSegmentedListContainerView(dataSource: self)
        return view
    }()
    
    private lazy var tipButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 23"), for: .normal)
        btn.addTarget(self, action: #selector(showTip), for: .touchUpInside)
        return btn
    }()
    
    private lazy var chatButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 4备份 2"), for: .normal)
        btn.addTarget(self, action: #selector(toChat), for: .touchUpInside)
        if let id = COUserManager.userInfo?.id, let id2 = userInfo?.id {
            btn.isHidden = id == id2
        }
        
        return btn
    }()
}

extension COHeViewController: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        2
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        return [sqVc, qaVc][index]
    }
    
    
}

extension COHeViewController {
    private func getMessage() {
        self.view.makeToastActivity(.center)
        CONetwork.sendRequest(provider: heProvider, target: .message(id: id)) { text in
            self.view.hideToastActivity()
            guard let userInfo = COHomeListModel.deserialize(from: text.dic) else {
                return
            }
            self.userInfo = userInfo
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }

    }
    
    @objc
    private func toChat() {
        let vc = COSendViewController()
        vc.userAvatar = self.userInfo?.sculpture ?? ""
        vc.userName = self.userInfo?.nickName ?? ""
        vc.userId = "\(self.userInfo?.id ?? 0)"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc
    private func folloUser() {
        self.follo(userInfo?.id ?? 0, isFollo: !(userInfo?.follow ?? false))
    }
}
